import React from 'react';
import {connect} from 'dva';
import { Accordion, List, Button, Toast, Switch, InputItem } from 'antd-mobile';
import styles from './index.less';
import addReimbursementInfo from '@/components/addReimbursementInfo';
import SeModal from '@/components/searchEmployee';
import UserServices from '@/services/user';
import { requestSuccess, getMastId } from '@/utils/tools';
import {
  selectFile,
  openWebview
} from '@/utils/cordova';
/**
 * 报销
 */
class cReimbursementDetails extends React.Component {
  constructor(props) {
    super(props);

    this.state = {

    }
  }

  handleShowPanel = () => {
    addReimbursementInfo.open({
      companyCode: this.props.detail.mast.companyCode,
      success: (arr) => {
        this.props.dispatch({type: 'detail/changeMast', payload: {
          orsItems: arr
        }})
      }
    });
  }

  handleDelInfo = (e, item) => {
    e.stopPropagation();
    const id = getMastId();
    const idText = `${Object.keys(id)[0]}=${Object.values(id)[0]}`;
    const errorFn = (e) => {
      if(e){
        const message = e.message || 'Error';
        Toast.fail(message);
      }
    }
    UserServices.delelteReimbursementById(item.id, idText).then(res => {
      if(requestSuccess(res)){
        const arr = global._.filter(this.props.detail.mast.orsItems, child => {
          return child.id !== item.id;
        });
        Toast.success('Success');
        this.onChange(arr, 'orsItems');
      }else{
        const errorInfo = global._.get(res, 'data.errorMessageList');
        errorFn(new Error(errorInfo))
      }
    }).then(errorFn)
  }

  handleSelectedEmployee = (key)=>{
    if(!this.props.edit)return;
    SeModal.open({
      success: (result) => {
        this.onChange(result.employees, key);
        this.props.dispatch({type: 'detail/saveViewWorkflowEntry'});
      },
      cancel: () => {

      }
    })
  }

  handleClickUploadAttachment = (event) => {
    console.log(event);
    const file = event.target.files[0];
    const imgMasSize = 1024 * 1024 * 50; // 10MB

    // 检查文件类型
    // if(['jpeg', 'png', 'gif', 'jpg'].indexOf(file.type.split("/")[1]) < 0){
    //     // 自定义报错方式
    //     // Toast.error("文件类型仅支持 jpeg/png/gif！", 2000, undefined, false);
    //     return;
    // }

    // 文件大小限制
    if(file.size > imgMasSize ) {
        // 文件大小自定义限制
        Toast.error("文件大小不能超过50MB！", 2000);
        return;
    }


    const formData = new FormData();
    // 自定义formData中的内容
    const id = getMastId();

    // type
    formData.append('trsMastId', id.trsMastId);
    // size
    formData.append('attachmentType', 'proposal1_');
    // name
    formData.append('uploadFile', file);
    // 上传图片
    this.uploadFile(formData);
  }

  uploadFile = (formData) => {
      const xhr = new XMLHttpRequest();
      Toast.loading('Uploading...', 0);

      // 进度监听
      xhr.upload.addEventListener('progress', (e)=>{
        console.log(e.loaded / e.total);
      }, false);
      // 加载监听
      // xhr.addEventListener('load', ()=>{console.log("加载中");}, false);
      // 错误监听
      xhr.addEventListener('error', ()=>{
        Toast.error("Upload Error");
        Toast.hide();
      }, false);
      xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
              const result = JSON.parse(xhr.responseText);
              if (xhr.status === 200) {
                  // 上传成功
                  Toast.success('Upload Success');
                  Toast.hide();
                  this.props.dispatch({type: 'detail/getData'});
              } else {
                  // 上传失败
                  Toast.error("Upload Error");
                  Toast.hide();
              }
          }
      };
      console.log(UserServices.getUploadFileUrl());
      xhr.open('POST', UserServices.getUploadFileUrl() , true);
      xhr.send(formData);
  }

  handleDelAttachment = (e, item) => {
    e.stopPropagation();
    UserServices.deleteAttachment({
      fileId: item.id,
      trsMastId: item.attachToId
    }).then(res => {
      if(requestSuccess(res)){
        Toast.success('Success');
        const arr = this.props.detail.mobileAttachmentListProposal1.filter(child => {
          return child.id !== item.id;
        });
        this.props.dispatch({type: 'detail/changeDetail', payload: {
          mobileAttachmentListProposal1: arr
        }});
      }
    }).catch(err => {
      Toast.fail(err.meesage || 'error');
    })
  }

  handlePreviewFile = (e, item) => {
    e.stopPropagation();
    const url = UserServices.getDownloadFileUrl(item.id);
    console.log(url);
    openWebview({url, title: 'Preview'}).then(res => {
      if(res.status == -1){
        window.open(url);
      }
    })
  }

  onChange = (value, key) => {
    this.props.dispatch({type: 'detail/changeMast', payload: {
      [key]: value
    }});
  }

  render(){
    const encrypt = (account) => {
      if(account && account.length > 4){
        return account.substr(0, 4) + '******' + account.substr(account.length - 4, account.length)
      }else{
        return '';
      }
    }
    return (
      <div className={styles.baseList}>
        {
          this.props.edit
          ?
          <div className={styles.item}>
            <div className={styles.des}>*Reimbursement Needed</div>
            <div className={styles.value}>
              <Switch checked={this.props.detail.mast.needReimbursement} onChange={(value) => this.onChange(value, 'needReimbursement')}></Switch>
            </div>
          </div>
          :
          <div className={styles.item}>
            <div className={styles.des}>*Reimbursement Needed</div>
              {/*needReimbursement是被转化的值*/}
            <div className={styles.value}>{this.props.detail.mast && this.props.detail.mast.needReimbursement ? 'YES':'NO'}</div>
          </div>
        }
        {
          this.props.detail.mast.needReimbursement
          ?
          <div>
            <div className={styles.item}>
              <div className={styles.des}>*Payee</div>
              <div className={styles.value} onClick={() => this.handleSelectedEmployee('payee')}>
                {this.props.detail.mast && this.props.detail.mast.payee || 'Select'}
              </div>
            </div>
            <div className={styles.item}>
              <div className={styles.des}>AccountHolder</div>
              <div className={styles.value}>
                {
                  this.props.edit
                  ?
                  <InputItem
                    clear
                    placeholder="click input"
                    value={this.props.detail.mast.accountHolder}
                    onChange={(value) => this.onChange(value, 'accountHolder')}
                  ></InputItem>
                  :
                  this.props.detail.mast && this.props.detail.mast.accountHolder
                }
              </div>
            </div>
            <div className={styles.item}>
              <div className={styles.des}>Bank Account</div>
              <div className={styles.value}>
                {
                  this.props.edit
                  ?
                  <InputItem
                    clear
                    placeholder="click input"
                    value={this.props.detail.mast.bankAccount}
                    onChange={(value) => this.onChange(value, 'bankAccount')}
                  ></InputItem>
                  :
                  this.props.detail.mast && encrypt(this.props.detail.mast.bankAccount)
                }
              </div>
            </div>
            <div className={styles.item}>
              <div className={styles.des}>Bank Name</div>
              <div className={styles.value}>
                {
                  this.props.edit
                  ?
                  <InputItem
                    clear
                    placeholder="click input"
                    value={this.props.detail.mast.bankName}
                    onChange={(value) => this.onChange(value, 'bankName')}
                  ></InputItem>
                  :
                  this.props.detail.mast && this.props.detail.mast.bankName
                }
              </div>
            </div>
            <div className={`${styles.item} ${styles.blockItem}`}>
              <div className={styles.des}>Item Detail</div>
              <div className={styles.value}>
                <div className={styles.labels}>
                  <div className={styles.label}>
                    Expense
                  </div>
                  <div className={styles.label}>
                    RMB Equiv
                  </div>
                  {
                    this.props.edit
                    ?
                    <div className={styles.smallLabel}>
                      Action
                    </div>
                    :
                    null
                  }
                </div>
                <Accordion className={styles.cList} onChange={this.onChange}>
                  {
                    this.props.detail.mast && this.props.detail.mast.orsItems && this.props.detail.mast.orsItems.map((item, index) => {
                      const headerDom = (cc) => {
                        return (
                          <div className={styles.headerValues}>
                            <div>{cc.expenseDetail}</div>
                            <div>{cc.amtRMB}</div>
                            {
                              this.props.edit
                              ?
                              <div className={styles.smallDiv}>
                                <Button onClick={(e) => this.handleDelInfo(e, item)} style={{padding: '0px 5px'}}>Delete</Button>
                              </div>
                              :
                              null
                            }
                          </div>
                        )
                      }
                      return (
                        <Accordion.Panel header={headerDom(item)} key={index}>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Expense</div>
                            <div className={styles.cValue}>{item.expenseDetail}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Expense Date From	</div>
                            <div className={styles.cValue}>{global.moment(item.expenseDateFrom).format('YYYY-MM-DD')}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Expense Date To</div>
                            <div className={styles.cValue}>{global.moment(item.expenseDateTo).format('YYYY-MM-DD')}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>WBS Code</div>
                            <div className={styles.cValue}>{item.wbsCode}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Country</div>
                            <div className={styles.cValue}>{item.country}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>City</div>
                            <div className={styles.cValue}>{item.city}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Amount</div>
                            <div className={styles.cValue}>{item.claimAmt}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Currency</div>
                            <div className={styles.cValue}>{item.currency}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Exchange Rate Date</div>
                            <div className={styles.cValue}>{global.moment(item.exchangeRateDate).format('YYYY-MM-DD')}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Exchange Rate RMB</div>
                            <div className={styles.cValue}>{item.exchangeRMB}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>RMB Equiv</div>
                            <div className={styles.cValue}>{item.amtRMB}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Remark</div>
                            <div className={styles.cValue}>{item.remark}</div>
                          </div>
                        </Accordion.Panel>
                      )
                    })
                  }
                </Accordion>
                {
                  !this.props.edit
                  ?
                  null
                  :
                  <Button style={{width: '150px', margin: '5px'}} onClick={this.handleShowPanel}>Add</Button>
                }
              </div>
            </div>
            <div className={`${styles.item} ${styles.blockItem}`}>
              <div className={styles.des}>Attachments</div>
              <div className={styles.value}>
                <div className={styles.labels}>
                  <div className={styles.label}>
                    File Name
                  </div>
                  <div className={styles.smallLabel}>
                    Action
                  </div>
                </div>
                <Accordion className={styles.cList} onChange={this.onChange}>
                  {
                    this.props.detail.mobileAttachmentListProposal1  && this.props.detail.mobileAttachmentListProposal1.map((item, index) => {
                      const headerDom = (cc) => {
                        return (
                          <div className={styles.headerValues}>
                            <div>{cc.fileName}</div>
                            {
                              this.props.edit
                              ?
                              <div className={styles.smallDiv}>
                                <Button onClick={(e) => this.handleDelAttachment(e, cc)} style={{padding: '0px 5px'}}>Delete</Button>
                              </div>
                              :
                              null
                            }
                            <div className={styles.smallDiv}>
                              <Button onClick={(e) => this.handlePreviewFile(e, cc)} style={{padding: '0px 5px'}}>Preview</Button>
                            </div>

                          </div>
                        )
                      }
                      return (
                        <Accordion.Panel header={headerDom(item)} key={index}>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>File Name</div>
                            <div className={styles.cValue}>{item.fileName}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Author</div>
                            <div className={styles.cValue}>{`${item.author} ${item.authorName}`}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Create Date</div>
                            <div className={styles.cValue}>{global.moment(item.createDate).format('YYYY-MM-DD HH:mm:ss')}</div>
                          </div>
                        </Accordion.Panel>
                        )
                      })
                    }
               </Accordion>
               {
                 !this.props.edit
                 ?
                 null
                 :
                 <Button style={{width: '150px', margin: '5px', position: 'relative'}}>
                   Add
                   <input className={styles.hiddenFileInput} refs="hiddenFileInput" type='file' accept="*" onChange={this.handleClickUploadAttachment}/>
                 </Button>
               }
              </div>
            </div>
          </div>
          :
          null
        }
      </div>
    )
  }
}


function mapStateToProps(state) {
  return {
    ...state.detail
  }
}
export default connect(mapStateToProps)(cReimbursementDetails);
